﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AutoGear.BLL;
using Entity;
using ECommerce.DAL;
using System.IO;
using System.Text;


public partial class controls_wucquickInvoiceWithPrice : System.Web.UI.UserControl
{
    private ProductPurchaseOrder _order;
    public ProductPurchaseOrder Order
    {
        get
        {
            if (_order == null)
            {
                if (orderId != null)
                {
                    _order = new ProductPurchaseOrder(orderId);
                    AutoGearSessionManager.OrderNumber = null;
                }
            }
            return _order;
        }
    }

    private string orderId;
    public string ORDERID
    {
        get { return orderId; }
        set { orderId = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Session["count"] = 0;
            if (Order == null)
            {

            }
            else
            {
                CustomCollection<TblGiftCertificateOrderItems> Giftitems = TblGiftCertificateOrderItems.GetTblGiftCertificateOrderItemsByOrderId(_order.OrderId);

                if (Order.ShoppingCart == null || Order.ShoppingCart.CartItems.Count <= 0)
                {
                    if (Giftitems == null && Giftitems.Count <= 0)
                    {
                        Response.Redirect(AutoGear.BLL.CustomSiteMap.ShoppingCart);
                    }
                }
                BindData();
            }
        }
    }
    private void BindData()
    {
        BindProductList();
        //if (Order.GIftCardMessage.Length > 0)
        //{
        //    trsubTotal.Visible = false;
        //    trTotal.Visible = false;
        //}

        CreditCard card = (CreditCard)Order.CreditCard;
        ShoppingCart cart = Order.ShoppingCart;
        AutoGear.BLL.Address billingAddress = (AutoGear.BLL.Address)Order.BillingAddress;
        AutoGear.BLL.Address shippingAddress = (AutoGear.BLL.Address)Order.ShippingAddress;

        lblDate.Text = Order.OrderDate.ToShortDateString();
        lblRequestDeliveryDate.Text = Order.RequestedDeliveryDate.ToShortDateString();
        lblOrderNo.Text = Order.OrderNumber;
        ltlSalesPerson.Text = Order.SPName;
        TblUserOrder customer = TblUserOrderExtended.GetTblUserOrderByOrderId(Order.OrderId);
        if (customer != null)
            ltlCustomer.Text = customer.UserId.ToString();

        string Shippingmethod = string.Empty;
        if (Order.ProductShipping.ProductShippingMethod == "1")
        {
            Shippingmethod = "Ground";
        }
        else if (Order.ProductShipping.ProductShippingMethod == "2")
        {
            Shippingmethod = "3 Day Select";
        }
        else if (Order.ProductShipping.ProductShippingMethod == "3")
        {
            Shippingmethod = "2nd Day Air";
        }
        else if (Order.ProductShipping.ProductShippingMethod == "4")
        {
            Shippingmethod = "Next Day Air";
        }
        lblShipmentStatus.Text = Shippingmethod;
        lblSubTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cart.SubTotal + cart.GiftSubTotal); ;
        lblCouponDiscount.Text = "-" + ECommerce.Library.ECommerce.Utility.FormatPriceText(Order.CouponDiscount);
        lblShippingHandling.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(Order.ProductShipping.ProductShippingCost);
        lblTax.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(Order.TaxAmount);
        lblTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(Order.TotalAmount);

        lblBillingFirstName.Text = billingAddress.FirstName;
        lblBillingLastName.Text = billingAddress.LastName;
        lblBillingEmailAddress.Text = billingAddress.EmailAddress;
        lblBillingAddress.Text = billingAddress.AddressLine1 + "\n" + billingAddress.AddressLine2;
        if (billingAddress.TelephoneNumber.Length > 3)
            lblBillingPhone.Text = "Primary Phone:" + billingAddress.TelephoneNumber;
        if (billingAddress.TelephoneNumber2.Length > 3)
            lblBillingPhone2.Text = "Secondary Phone: " + billingAddress.TelephoneNumber2;
        lblBillingCity.Text = billingAddress.City;
        lblBillingState.Text = billingAddress.AddressState;
        lblBillingZipCode.Text = billingAddress.ZipCode;

        lblShippingFirstName.Text = shippingAddress.FirstName;
        lblShippingLastName.Text = shippingAddress.LastName;
        lblShippingAddress.Text = shippingAddress.AddressLine1 + "\n" + shippingAddress.AddressLine2;
        lblShippingEmailAddress.Text = shippingAddress.EmailAddress;
        lblShippingPhone.Text = shippingAddress.TelephoneNumber;
        lblShippingCity.Text = shippingAddress.City;
        lblShippingState.Text = shippingAddress.AddressState;
        lblShippingZipCode.Text = shippingAddress.ZipCode;
        lblShippingState.Text = shippingAddress.AddressState;
        if (card != null)
        {
            if (Order.CreditCardAmount > 0)
                lblCreditCard.Text = String.Format("{0:C}", Order.CreditCardAmount) + " has been deducted from " + card.CardType + " ending in " + SiteUtility.HideCharacter(card.CardNumber, '*', card.CardNumber.Length - 4, true);
            else
                trCreaditCard.Style.Add("display","none");
        }
        StringBuilder SB = new StringBuilder();
        StringWriter SW = new StringWriter(SB);
        HtmlTextWriter htmlTW = new HtmlTextWriter(SW);
        quickInvoice.RenderControl(htmlTW);
        string dataHTML = SB.ToString();
        // dataHTML = dataHTML.Replace("App_Style/", "E:/Projets/Polana/autogear-web/App_Style/");
        StringReader reader = new StringReader(dataHTML);
     //   CreatePDFCrowdPDF(dataHTML);
    }

    private void CreatePDFCrowdPDF(string htmlContent)
    {
        System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
        try
        {
            // create an API client instance
            pdfcrowd.Client client = new pdfcrowd.Client("polana", "2563aec6de3d0058353e599c653084cc");

            // convert a web page and write the generated PDF to a memory stream
            MemoryStream mStream = new MemoryStream();
            client.convertHtml(htmlContent, mStream);
            FileStream outStream = File.OpenWrite(Request.PhysicalApplicationPath + "pdf\\" + "" + orderId + ".pdf");
            mStream.WriteTo(outStream);
            outStream.Flush();
            outStream.Close();

        }
        catch (pdfcrowd.Error why)
        {
            Response.Write(why.ToString());
        }

    }
    private void BindProductList()
    {
        ShoppingCart cart = Order.ShoppingCart;
        rptProduct.DataSource = cart.CartItems;
        rptProduct.DataBind();

        CustomCollection<TblGiftCertificateOrderItems> gftItems = TblGiftCertificateOrderItems.GetTblGiftCertificateOrderItemsByOrderId(_order.OrderId);
        if (gftItems != null)
        {
            int temp_code = gftItems[0].GiftCertificateId;
            TblGiftCertificate CurrentGiftCertificate = TblGiftCertificate.GetTblGiftCertificateByGiftCertificateId(temp_code);

            GiftItem giftItem = new GiftItem(CurrentGiftCertificate.GiftCertificateId.ToString(), CurrentGiftCertificate.Code, CurrentGiftCertificate.FromEmailAddress, CurrentGiftCertificate.FromName,
                CurrentGiftCertificate.ToEmailAddress, CurrentGiftCertificate.ToName, CurrentGiftCertificate.Message, CurrentGiftCertificate.Quantity, CurrentGiftCertificate.PriceAmount, CurrentGiftCertificate.DateCreated, CurrentGiftCertificate.DateExpired);

            cart.AddGiftItem(giftItem);

            rptGiftCertificate.DataSource = cart.GiftItems;
            rptGiftCertificate.DataBind();
        }

        if (rptProduct.Items.Count == 0)
        {
            rptProduct.Visible = false;
        }
        if (rptGiftCertificate.Items.Count == 0)
        {
            rptGiftCertificate.Visible = false;
        }
        if (Order.Substitute.Length > 5)
        {
            lblSubstitute.Text = Order.Substitute;
            lblSubstitute.Visible = false;
        }

        //imgGIftCard.ImageUrl = Order.GiftCardImageUrl;
        if (!String.IsNullOrEmpty(Order.SpecialInstruction))
        {
            lblComments.Visible = true;
            lblComments.Text = "<br/><b>Comments</b> :  " + Order.SpecialInstruction;
            lblComments.Style.Add("height", "auto");
            lblComments.Style.Add("display", "block");
        }
        if (!String.IsNullOrEmpty(Order.GIftCardMessage))
        {
            lblGiftCardMsg.Visible = true;
            lblGiftCardMsg.Text = "<br/><b>Gift Message</b> :  " + Order.GIftCardMessage;
            lblGiftCardMsg.Style.Add("height", "auto");
            lblGiftCardMsg.Style.Add("display", "block");
        }
    }
    protected void rptProduct_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            //if (Order.GIftCardMessage.Length > 0)
            //{
            //    Literal ltlItemNumber = (Literal)e.Item.FindControl("ltlItemNumber");
            //    ltlItemNumber.Visible = false;

            //    Literal ltlPrice = (Literal)e.Item.FindControl("ltlPrice");
            //    ltlPrice.Visible = false;
            //    Literal ltlTotal = (Literal)e.Item.FindControl("ltlTotal");
            //    ltlTotal.Visible = false;

            //}
        }

        else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            CartItem cartItem = (CartItem)e.Item.DataItem;
            if (cartItem != null)
            {
                HyperLink hlkItem = (HyperLink)e.Item.FindControl("hlkItem");
                if (cartItem.Product.ProductName != null)
                {
                    hlkItem.Text = cartItem.Product.ProductName;
                    hlkItem.Style.Add("text-decoration", "none");
                }
                else
                {
                    hlkItem.Text = "Name Deleted";
                    hlkItem.Style.Add("text-decoration", "none");
                }
                Label lblQuantity = (Label)e.Item.FindControl("lblQuantity");
                lblQuantity.Text = cartItem.Quantity.ToString();


                Label lblItemNumber = (Label)e.Item.FindControl("lblItemNumber");
                if (cartItem.Product.ItemNumber != null)
                    lblItemNumber.Text = cartItem.Product.ItemNumber;
                else
                    lblItemNumber.Text = "Deleted";

                Label lblItemPrice = (Label)e.Item.FindControl("lblItemPrice");
                lblItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.UnitPrice);
                Label lblItemTotal = (Label)e.Item.FindControl("lblItemTotal");
                lblItemTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(cartItem.ItemTotal);
                //if (Order.GIftCardMessage.Length > 0)
                //{
                //    lblItemNumber.Visible = false;
                //    lblItemPrice.Visible = false;
                //    lblItemTotal.Visible = false;
                //}
            }
        }
        else if (e.Item.ItemType == ListItemType.Footer)
        {
        }
    }
    protected void rptGiftCertificate_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Header)
        {
            //if (Order.GIftCardMessage.Length > 0)
            //{
            //    Literal ltlgiftPrice = (Literal)e.Item.FindControl("ltlgiftPrice");
            //    ltlgiftPrice.Visible = false;
            //    Literal ltlgiftTotal = (Literal)e.Item.FindControl("ltlgiftTotal");
            //    ltlgiftTotal.Visible = false;

            //}
        }

        else if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            GiftItem giftItem = (GiftItem)e.Item.DataItem;

            Label lblGiftName = (Label)e.Item.FindControl("lblGiftName");
            lblGiftName.Text = "Name: " + giftItem.ToName + "  " + "Email: " + giftItem.ToEmailAddress;
            Label lblGiftQuantity = (Label)e.Item.FindControl("lblGiftQuantity");
            lblGiftQuantity.Text = giftItem.Quantity.ToString();


            Label lblGiftItemPrice = (Label)e.Item.FindControl("lblGiftItemPrice");
            lblGiftItemPrice.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(giftItem.UnitPrice);

            Label lblGiftItemTotal = (Label)e.Item.FindControl("lblGiftItemTotal");
            lblGiftItemTotal.Text = ECommerce.Library.ECommerce.Utility.FormatPriceText(giftItem.ItemTotal);
            //if (Order.GIftCardMessage.Length > 0)
            //{
            //    lblGiftItemPrice.Visible = false;
            //    lblGiftItemTotal.Visible = false;
            //}
        }
        else if (e.Item.ItemType == ListItemType.Footer)
        {

        }

    }

}